import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login } from '../../services/api';

interface Props{
    isLogin:()=>void,
    setRegisVisible:(visible:boolean)=>void
}

function Login(props:Props) {
    const onFinish = async (values: any) => {
        console.log('Received values of form: ', values);
        try {
            let result = await login(values.username, values.password)
            if (result.stat === 'ok') {
                sessionStorage.setItem("username", values.username)
                if (values.remember) {
                    sessionStorage.setItem("password", values.password)
                } else {
                    sessionStorage.setItem("password", "")
                }
                sessionStorage.setItem("token", String(result.data?.token))
                props.isLogin()
            } else {
                if(result.stat==='Err_User_Not_Found')
                message.error('用户名或密码错误')
            }
        } catch (error) { }
    };
    return (
        <Form
            name="normal_login"
            className="login-form"
            initialValues={sessionStorage.getItem("username") !== "" ?
                (sessionStorage.getItem("password") !== "" ? 
                { username: sessionStorage.getItem("username"), password: sessionStorage.getItem("password"), remember: true } : 
                { username: sessionStorage.getItem("username"), remember: false })
                : { remember: true }}
            onFinish={onFinish}
        >
            <Form.Item
                name="username"
                rules={[{ required: true, message: '请填写用户名' }]}
            >
                <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
            </Form.Item>
            <Form.Item
                name="password"
                rules={[{ required: true, message: '请填写密码' }]}
            >
                <Input
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    type="password"
                    placeholder="Password"
                />
            </Form.Item>
            <Form.Item>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                    <Checkbox>记住密码</Checkbox>
                </Form.Item>
            </Form.Item>

            <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button form-button" >
                    立即登录
                </Button>
                <a onClick={()=>props.setRegisVisible(true)}>没有账号？立即注册</a>
            </Form.Item>
        </Form>
    );

}
export default Login